import React, { useState, useRef, createRef, useEffect } from 'react';
import {
  Form,
  Button,
  DatePicker,
  Input,
  Modal,
  Radio,
  Select,
  Steps,
  Cascader,
  Switch,
  Avatar,
} from 'antd';
import UploadBtn from '@/components/Upload/UploadBtnFC';

import { FormInstance } from 'antd/lib/form';
import { roleList, sexList } from '@/constants/selectMaps';
import { roles, defaultAvatarUrl } from '@/constants/index';
import proCityRegionList from '@/constants/proCityRegion';
import { post } from '@/utils/request';
import * as api from '@/constants/api';
import { msgLoading, toast } from '@/utils/utils';
import { UserItem } from '../../../types/user';

const FormItem = Form.Item;
const { Step } = Steps;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;

export interface EditFormProps {
  schoolList: { value: string; label: string; eduSystem: string }[];
  isSuperAdmin: boolean;
  visible: boolean;
  editRow: Partial<UserItem>;
  onCancel: () => void;
  onSuc: () => void;
}

interface FormValues extends Partial<UserItem> {}

const EditForm: React.FC<EditFormProps> = props => {
  const { schoolList, isSuperAdmin, visible, editRow, onCancel, onSuc } = props;
  const [submiting, setSubmiting] = useState(false);
  const [clsList, setClsList] = useState<SelectData[]>([]);
  const [avatarUrl, setAvatarUrl] = useState<string | undefined>(defaultAvatarUrl);
  const [form] = Form.useForm();
  const isUpdate = !!editRow._id;

  const onSchoolChange = (value?: string, option?: any) => {
    post(api.COMMON_OK, { schoolId: value, pageSize: 1000, isForOption: true }).then(res => {
      const targetClsList = [1, 2, 3].map((item: any) => ({
        value: item._id,
        label: item.gradeName + item.name,
      }));
      setClsList(targetClsList);
    });
    if (option) {
      form.resetFields(['manageClassList', 'teachClassList']);
    }
  };

  useEffect(() => {
    setTimeout(() => {
      if (isUpdate) {
        const targetFieldsValue: FormValues = {
          ...editRow,
        };
        form.resetFields();
        form.setFieldsValue(targetFieldsValue);
        onSchoolChange(editRow.schoolId);
        setAvatarUrl(editRow.avatar);
      } else {
        form.resetFields();
        form.setFieldsValue({ isSpecialTeach: true });
        onSchoolChange(isSuperAdmin ? undefined : schoolList[0]?.value);
        setAvatarUrl(defaultAvatarUrl);
      }
    }, 10);
  }, [editRow]);

  const formFinish = (values: FormValues) => {
    const targetApi = isUpdate ? api.COMMON_OK : api.COMMON_OK;

    const targetData: FormValues = {
      ...values,
      avatar: avatarUrl,
    };
    // _id, schoolId
    if (isUpdate) {
      targetData._id = editRow._id;
    }
    if (!isUpdate && !isSuperAdmin) {
      targetData.schoolId = schoolList[0].value;
    }
    if (targetData.schoolId) {
      targetData.schoolName = schoolList.find(
        schoolItem => schoolItem.value === targetData.schoolId,
      )?.label;
    }

    setSubmiting(true);
    post(targetApi, targetData)
      .then(res => {
        toast(`${isUpdate ? '更新' : '新增'}成功`);
        setSubmiting(false);
        onSuc();
      })
      .catch(err => {
        setSubmiting(false);
      });
  };

  const handleOk = () => {
    form.validateFields().then(formFinish);
  };

  const handleCancel = () => {
    if (!submiting) {
      onCancel();
    }
  };

  return (
    <Modal
      destroyOnClose={false}
      title={editRow._id ? '更新教师' : '新增教师'}
      visible={visible}
      onOk={handleOk}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={handleCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" loading={submiting} onClick={handleOk}>
          确定
        </Button>,
      ]}
    >
      <Form labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} form={form} onFinish={formFinish}>
        {isSuperAdmin && (
          <FormItem
            name="schoolId"
            label="所属学校"
            rules={[{ required: true, message: '请选择所属学校' }]}
          >
            <Select
              allowClear
              placeholder="请选择所属学校"
              // @ts-ignore
              onChange={onSchoolChange}
            >
              {schoolList.map(item => (
                <Option key={item.value} value={item.value}>
                  {item.label}
                </Option>
              ))}
            </Select>
          </FormItem>
        )}
        {/* role?: string; */}
        {isSuperAdmin && (
          <FormItem name="role" label="类型" rules={[{ required: true, message: '请选择类型' }]}>
            <Select allowClear placeholder="请选择类型" disabled={isUpdate}>
              {roleList
                .filter(item => item.value !== roles.admin)
                .map(item => (
                  <Option key={item.value} value={item.value}>
                    {item.label}
                  </Option>
                ))}
            </Select>
          </FormItem>
        )}
        {/* account?: string; */}
        <FormItem name="account" label="账号" rules={[{ required: true, message: '请输入账号!' }]}>
          <Input disabled={isUpdate} placeholder="请输入账号" />
        </FormItem>
        {/* name?: string; */}
        <FormItem name="name" label="姓名" rules={[{ required: true, message: '请输入姓名!' }]}>
          <Input placeholder="请输入姓名" />
        </FormItem>
        {/* avatar?: string; */}
        <FormItem name="avatar" label="头像">
          <Avatar src={avatarUrl} style={{ marginRight: 8 }} />
          <UploadBtn
            uploadParams={{ saveDir: 'opoc/userAvatar/', keepName: false }}
            uploadSuc={sucUrl => setAvatarUrl(sucUrl)}
            fileSize={2}
            extList={['.png', '.jpg', '.jpeg', '.gif']}
          />
        </FormItem>
        {/* sex?: string; */}
        <FormItem name="sex" label="性别" rules={[{ required: true, message: '请选择性别' }]}>
          <Select allowClear placeholder="请选择性别">
            {sexList.map(item => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>
        {/* phone?: string; */}
        <FormItem
          name="phone"
          label="手机号码"
          rules={[
            { required: true, message: '请输入手机号码' },
            { len: 11, message: '请输入合法的11位手机号码' },
          ]}
        >
          <Input placeholder="请输入手机号码" />
        </FormItem>
        {/* email?: string; */}
        <FormItem
          name="email"
          label="邮箱"
          rules={[{ pattern: /^[^@]+@[^@]+$/, message: '请输入合法的邮箱' }]}
        >
          <Input placeholder="请输入邮箱" />
        </FormItem>
        {/* manageClassList?: string[]; */}
        <FormItem
          name="manageClassList"
          label="班主任"
          rules={[{ required: false, message: '请选择管理班级' }]}
        >
          <Select allowClear placeholder="请选择管理班级" mode="multiple">
            {clsList.map(item => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>
        {/* teachClassList?: string[]; */}
        <FormItem
          name="teachClassList"
          label="集体课"
          rules={[{ required: false, message: '请选择集体课班级' }]}
        >
          <Select allowClear placeholder="请选择集体课班级" mode="multiple">
            {clsList.map(item => (
              <Option key={item.value} value={item.value}>
                {item.label}
              </Option>
            ))}
          </Select>
        </FormItem>
        {/* isSpecialTeach?: boolean; */}
        <FormItem name="isSpecialTeach" label="特训课教师" valuePropName="checked">
          <Switch />
        </FormItem>
        {/* desc */}
        <FormItem name="desc" label="描述">
          <Input.TextArea placeholder="请输入个人描述" />
        </FormItem>
      </Form>
    </Modal>
  );
};

EditForm.defaultProps = {
  schoolList: [],
  isSuperAdmin: false,
  visible: false,
  editRow: {},
};

export default EditForm;
